//
//  VWPlayerFinishedStateLayer.swift
//  VideoWatcher
//
//  Created by JY_NEW on 2021/10/19.
//  Copyright © 2021 JunYue. All rights reserved.
//

import ijkPlayerManager
import UIKit
import UICreate

/// 播放完成状态
class VWPlayerFinishedStateLayer: VWPlayerBaseLayer {
    
    override var category: VideoPlayerLayerCategory {
        return .state
    }

    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.status.addTarget(self, action: #selector(self.onStatusChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.status.removeTarget(self)
    }
    
    override func loadContainerView(_ containerView: UIView) {
        containerView.backgroundColor = .black
        containerView.add(self.contentView, layout: .center)
    }
    
    @objc func onStatusChanged() {
        // 播放结束
        if let player = self.playerManager {
            if player.status.isFinished {
                //有下一集
                if self.context?.hasNext ?? false {
                    self.deactive()
                    // 自动播放下一集
                    self.delegate?.onPlayerNext()
                }else{
                    self.active()
                }
            }else if player.status.isPlaying {
                self.deactive()
            }
        }
    }
    
    override func show(completion: @escaping () -> Void) {
        self.aniamteShow(for: self.contentView, completion: completion)
    }
    override func hide(completion: @escaping () -> Void) {
        self.aniamteHide(for: self.contentView, completion: completion)
    }
    
    // MARK: 界面控件
    
    lazy var contentView: UIView = {
        let button = FXButton(.image(.init(named:"vw_play_replay")), .image(position: .top), .title(insets: .top(8)),  .text("重播"), .font(.pingfang(medium: 13)), .color(.white), .event(self, #selector(self.onReplay)), .size(100))
        return button
    }()
    @objc func onReplay() {
        self.deactive()
        self.playerManager?.play(from: 0)
    }
}
